package com.whut.cristiano.autographbook.Activity;

import android.app.ProgressDialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.whut.cristiano.autographbook.MyApplication;
import com.whut.cristiano.autographbook.R;
import com.whut.cristiano.autographbook.Util.MD5Util;
import com.whut.cristiano.autographbook.Util.NetUtil;
import com.whut.cristiano.autographbook.Util.ToastUtil;
import com.whut.cristiano.autographbook.VO.UserVO;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/**
 * @author ykbboom
 * @email ykbpro@whut.edu.cn
 * @time 2017-1-27 10:28:39
 * 功能: 注册
 */
public class RegisterActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private static final int REFRESH_TIME = 1;//倒计时
    private static final int RESET_GET_VERIFY_CODE = 2;//倒计时结束可重新发送短信
    private static final int GET_VERIFY_CODE_SUCCESS = 3;//获取验证码成功
    private static final int SUBMIT_VERIFY_CODE_SUCCESS = 4;//提交验证码成功

    private ProgressDialog progressDialog;
    private Button getVerifyCodeBtn;//获取验证码
    private EditText accountNameEdit;//输入用户名
    private EditText passwordEdit;//输入密码
    private EditText phoneNumEdit;//输入手机号
    private EditText verifyCodeEdit;//输入验证码
    private LinearLayout chooseSchoolLinearlayout;
    private ListView placeListView;
    private ListView schoolListView;
    private TextView listTitle;//PopupWindow标题
    private TextView showSchoolTextView;
    private View parent;
    private PopupWindow popupWindow;
    private String[]provinceData = {"北京","上海","江苏","广东","湖北","山东","湖南"
            ,"福建","江西","安徽","东三省","陕西","川渝"};

    private Button registerAndLoginBtn;//注册并登陆
    private static int time = 60;//显示在验证码按钮上的倒计时

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case REFRESH_TIME:
                    getVerifyCodeBtn.setText("重新发送"+"("+time+")"+"秒");
                    break;
                case RESET_GET_VERIFY_CODE:
                    getVerifyCodeBtn.setText("发送验证码");
                    getVerifyCodeBtn.setBackgroundResource(R.drawable.verify_botton);
                    getVerifyCodeBtn.setClickable(true);
                    break;
                case GET_VERIFY_CODE_SUCCESS:
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        //回调完成
                        if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                            //获取验证码成功
                            ToastUtil.showToast(RegisterActivity.this,"验证码已发送");
                        }
                    }else{
                        ((Throwable)data).printStackTrace();
                    }
                    break;
                case SUBMIT_VERIFY_CODE_SUCCESS:
                    int event1 = msg.arg1;
                    int result1 = msg.arg2;
                    if (result1 == SMSSDK.RESULT_COMPLETE) {
                        //回调完成
                        if (event1 == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                            //提交验证码成功
                            showDialog(progressDialog);
                            NetUtil.RegAndLogin(new UserVO(accountNameEdit.getText().toString(),
                                            phoneNumEdit.getText().toString(),
                                            MD5Util.encodeToHex(passwordEdit.getText().toString()),showSchoolTextView.getText().toString())
                                    ,RegisterActivity.this,progressDialog);
                        }else{
                            ToastUtil.showToast(RegisterActivity.this,"验证码有误。");
                        }
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initSDK();
    }

    private void initSDK(){
        SMSSDK.initSDK(this,SMSSDK_APP_KEY,SMSSDK_APP_SECRET);
        EventHandler eventHandler = new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message message = new Message();
                if (event==SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    //获取验证码成功
                    message.what = GET_VERIFY_CODE_SUCCESS;
                }else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){
                    //提交验证码成功
                    message.what = SUBMIT_VERIFY_CODE_SUCCESS;
                }
                message.arg1 = event;
                message.arg2 = result;
                message.obj = data;
                handler.sendMessage(message);

            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            //toolbar后退按钮
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void initView(){
        progressDialog = new ProgressDialog(this);
        getVerifyCodeBtn = (Button) findViewById(R.id.get_verify_code_btn);
        getVerifyCodeBtn.setOnClickListener(this);
        accountNameEdit = (EditText) findViewById(R.id.account_name_edit);
        passwordEdit = (EditText) findViewById(R.id.password_edit);
        phoneNumEdit = (EditText) findViewById(R.id.phone_number_edit);
        verifyCodeEdit = (EditText) findViewById(R.id.verify_code_edit);
        registerAndLoginBtn = (Button) findViewById(R.id.register_login_btn);
        registerAndLoginBtn.setOnClickListener(this);
        chooseSchoolLinearlayout = (LinearLayout) findViewById(R.id.activity_choose_school_ll);
        chooseSchoolLinearlayout.setOnClickListener(this);
        showSchoolTextView = (TextView) findViewById(R.id.activity_show_school_textView);

        //初始化PopupWindow
        parent =  this.getWindow().getDecorView();
        View popView = View.inflate(this, R.layout.popwindow_choose_school, null);
        listTitle = (TextView) popView.findViewById(R.id.list_title);
        placeListView = (ListView) popView.findViewById(R.id.province);
        schoolListView = (ListView) popView.findViewById(R.id.school);
        placeListView.setOnItemClickListener(this);
        schoolListView.setOnItemClickListener(this);
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,provinceData);
        placeListView.setAdapter(adapter);

        int width = getResources().getDisplayMetrics().widthPixels * 3 / 4;
        int height = getResources().getDisplayMetrics().heightPixels * 3 / 5;
        popupWindow = new PopupWindow(popView, width, height);
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);//允许在外侧点击取消
    }
    private boolean isPhoneNum(String phoneNumber){
        boolean isValid = false;
   /*
    * 可接受的电话格式有：
    */
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
   /*
    * 可接受的电话格式有：
    */
        String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);

        Pattern pattern2 = Pattern.compile(expression2);
        Matcher matcher2 = pattern2.matcher(inputStr);
        if(matcher.matches() || matcher2.matches()) {
            isValid = true;
        }
        return isValid;
    }
    private boolean checkUserInfo(String userName,String userPass,String userSchool){
        if (userName==null||userPass==null||userSchool==null||userName.trim().equals("")||userPass.trim().equals("")){
            return false;
        }else
            return true;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.get_verify_code_btn:
                if (isPhoneNum(phoneNumEdit.getText().toString())){
                    SMSSDK.getVerificationCode("86",phoneNumEdit.getText().toString());
                    getVerifyCodeBtn.setClickable(false);
                    getVerifyCodeBtn.setBackgroundResource(R.drawable.verify_btn_press);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                while(time>0){
                                    Message message = new Message();
                                    message.what = REFRESH_TIME;
                                    handler.sendMessage(message);
                                    time--;
                                    Thread.sleep(1000);
                                }
                                Message message = new Message();
                                time = 60;
                                message.what = RESET_GET_VERIFY_CODE;
                                handler.sendMessage(message);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                }else {
                    ToastUtil.showToast(this,"请填写正确格式的手机号");
                    break;
                }
            case R.id.register_login_btn:
                if (checkUserInfo(accountNameEdit.getText().toString(),passwordEdit.getText().toString(),showSchoolTextView.getText().toString())){
                    SMSSDK.submitVerificationCode("86",phoneNumEdit.getText().toString(),
                            verifyCodeEdit.getText().toString());
                    Message message = new Message();
                    message.what = SUBMIT_VERIFY_CODE_SUCCESS;
                    handler.sendMessage(message);
                    break;
                }else{
                    ToastUtil.showToast(this,"请完善信息");
                    break;
                }

            case R.id.activity_choose_school_ll:
                showPopWindow();
                break;

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == placeListView) {
            String provinceName = (String) placeListView.getItemAtPosition(position);
            listTitle.setText("选择学校");
            placeListView.setVisibility(View.GONE);//隐藏地区
            schoolListView.setVisibility(View.VISIBLE);//显示学校
            NetUtil.getSchoolByProvince(provinceName,schoolListView);
        } else if (parent == schoolListView) {
            String schoolName = (String) schoolListView.getItemAtPosition(position);
            showSchoolTextView.setText(schoolName);
            placeListView.setVisibility(View.VISIBLE);
            schoolListView.setVisibility(View.GONE);
            listTitle.setText("选择地区");
            popupWindow.dismiss();
        }
    }

    private void showPopWindow()
    { popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);}
}

